package com.hnevc.eaxmliaorui;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnevc.eaxmliaorui.R;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShowActivity extends AppCompatActivity {

    private List<Food> foodList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //TODO 获取数据并更新界面
                //访问网络获取数据
                String url = "http://10.1.65.232:8080/RestaurantServer/Food/getFoods";
                Request request = new Request.Builder()
                        .url(url)
                        .get()
                        .build();
                OkHttpClient client = new OkHttpClient();

                Call call = client.newCall(request);
                try {
                    //得到结果
                    Response response = call.execute();
                    //处理结果
                    String data = response.body().string();
                    //使用Gson解析jsonstring
                    Gson gson = new Gson();
                    foodList = gson.fromJson(data, new TypeToken<List<Food>>(){}.getType());
                    //更新界面显示
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //获取列表控件
                            ListView listView = (ListView) findViewById(R.id.id_lv_data);
                            //构建适配器
                            MyBaseAdapter adapter = new MyBaseAdapter(ShowActivity.this,foodList);
                            //绑定适配器到ListView
                            listView.setAdapter(adapter);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();







    }
}
